import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'

// GET /api/orders - 获取所有订单
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const includeRelations = searchParams.get('include') === 'all'
    const customerId = searchParams.get('customer_id')
    const courseId = searchParams.get('course_id')

    const where: any = {}
    
    if (customerId) {
      where.customer_id = customerId
    }
    
    if (courseId) {
      where.course_id = parseInt(courseId)
    }

    const orders = await prisma.order.findMany({
      where,
      include: includeRelations ? { customer: true, course: true } : undefined,
      orderBy: { created_at: 'desc' }
    })

    return NextResponse.json({
      success: true,
      data: orders
    })
  } catch (error) {
    console.error('Error fetching orders:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to fetch orders' },
      { status: 500 }
    )
  }
}

// POST /api/orders - 创建订单
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    
    const { status, course_id, customer_id } = body

    // 验证必填字段
    if (!course_id || !customer_id) {
      return NextResponse.json(
        { success: false, error: 'Missing required fields: course_id and customer_id' },
        { status: 400 }
      )
    }

    const order = await prisma.order.create({
      data: {
        status: status || 0,
        course_id: parseInt(course_id),
        customer_id
      },
      include: { customer: true, course: true }
    })

    return NextResponse.json({
      success: true,
      data: order
    }, { status: 201 })
  } catch (error: any) {
    console.error('Error creating order:', error)
    
    // 如果是外键约束错误
    if (error.code === 'P2003') {
      return NextResponse.json(
        { success: false, error: 'Invalid course_id or customer_id' },
        { status: 400 }
      )
    }

    return NextResponse.json(
      { success: false, error: 'Failed to create order' },
      { status: 500 }
    )
  }
}
